package com.foxzzz.database;

import org.h2.tools.Server;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.UUID;

public class MyDatabase {
    private Server server=null;
    private String port=null;
    private String tcpUrl=null;
    private String localUrl=null;
    private String databasePath=null;
    private String user=null;
    private String password=null;


    //create database file
    public MyDatabase(String databasePath,String port,String user,String password){
        this.databasePath=databasePath;
        this.port=port;
        this.user=user;
        this.password=password;
        try {
            Class.forName("org.h2.Driver");
            try {
                //init databse
                localUrl= "jdbc:h2:./"+databasePath;
                Connection connection=DriverManager.getConnection(localUrl,user,password);
                connection.close();
            } catch (SQLException e) {
            }
        } catch (ClassNotFoundException e) {
        }

    }

    // return tcp url
    public String getTcpUrl(){
        return tcpUrl;
    }

    public String getLocalUrl(){
        return localUrl;
    }
    //return tcp connection
    //suggest use local connection
    public Connection getConnection(){
        Connection connection=null;
        try {
            connection=DriverManager.getConnection(tcpUrl,user,password);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return connection;
    }


    //start tcp server
    //then you can get tcpurl
    public void start(){
        try {
            server=Server.createTcpServer( "-tcp", "-tcpAllowOthers", "-tcpPort",
                    port);
            String url=server.getURL();
            tcpUrl=String.format("jdbc:h2:%s%s%s",url,"/./",databasePath);
            server.start();

        } catch (SQLException e) {
            server.stop();

        }

    }

    //stop tcp Server
    public void stop(){
        server.stop();
    }

    public static void main(String[] args) {



    }
}
